/*
 * @Author: chichiksky
 * @Date: 2022-03-24 21:57:06
 * @LastEditTime: 2022-04-02 15:11:00
 * @LastEditors: your name
 * @Description: 客户端课程列表显示页面
 * @FilePath: \web\src\router\class\classChild\course\index.jsx
 */

import "./index.css";
import {
  Drawer,
  Form,
  Button,
  Col,
  Row,
  Input,
  message,
  Space,
  DatePicker,
  Select
} from "antd";
import React, { useEffect, useState } from "react";
import request from "../../../../network/index";
import Cookie from "../../../../assets/common/cookie";
import CourseItem from "../../../../components/class/courseItem";
const requireContext = require.context(
  "../../../../assets/img/course/",
  true,
  /^\.\/.*\.jpg$/
);
const images = requireContext.keys().map(requireContext);
const Course = () => {
  const userInfo = Cookie.get("userInfo")
    ? JSON.parse(Cookie.get("userInfo"))
    : "";

  const [list, setList] = useState([]);
  const [classList, setClassList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [updataImg, setUpdataImg] = useState("");
  const { Search } = Input;
  const [form] = Form.useForm();
  const { RangePicker } = DatePicker;
  const { Option } = Select;

  useEffect(() => {
    getList();
    Number(userInfo.type) === 2 && getClassList();
  }, []);

  // 获取课程列表
  const getList = async () => {
    const url =
      (Number(userInfo.type) === 2
        ? "/teacher?id="
        : "/student?id=") + userInfo.id;
    const { list } = await request.get(url);
    console.log("courseList", list);
    setList(list);
  };

  // 获取班级列表
  const getClassList = async () => {
    const {list} = await request.get('/teacher/class');
    console.log("classList", list);
    const newList = list.map(e => <Option key={e._id}>{e.th+'-'+e.name}</Option>)
    setClassList(newList);
  };


  const onSearch = (value) => console.log(value);

  const showDrawer = () => {
    form.resetFields();
    setUpdataImg("");
    setVisible(true);
  };

  const onClose = () => {
    setVisible(false);
  };

  const onSubmit = async () => {
    const name = form.getFieldValue("name");
    const _class = form.getFieldValue("_class");
    const time = form.getFieldValue("time")
      ? form
          .getFieldValue("time")
          .map((e) => e._d)
          .join("~")
      : null;
    if (!name) {
      message.error("请填写课题名称", 1.5);
    } else {
      if (!time) {
        message.error("请填写开课时间", 1.5);
      } else {
        if (!!!updataImg) {
          message.error("请选择课程封面", 1.5);
        } else {
          if(!_class.length){
            message.error("请选择授课班级", 1.5);
          } else {
            const params = {
              name,
              time,
              teacher: userInfo.id,
              teacher_name: userInfo.username,
              url: updataImg,
              _class
            };
            await request.post("/teacher", params);
            onClose();
            getList();
            message.success("新建课程成功", 1.5);
          }
        }
      }
    }
  };

  const selectedImg = ({ target }) => {
    console.log("src", target.currentSrc);
    setUpdataImg(target.currentSrc);
  };

  return (
    <div id="course">
      <div className="course-head">
        <Search placeholder="搜索" onSearch={onSearch} enterButton />
        {Number(userInfo.type) === 2 ? (
          <Button type="primary" onClick={showDrawer}>
            新建课程
          </Button>
        ) : (
          ""
        )}
        <Drawer
          title="新建课程"
          width={720}
          onClose={onClose}
          visible={visible}
          bodyStyle={{ paddingBottom: 80 }}
          extra={
            <Space>
              <Button onClick={onClose}>取消</Button>
              <Button onClick={onSubmit} type="primary" htmlType="submit">
                提交
              </Button>
            </Space>
          }
        >
          <Form
            form={form}
            layout="vertical"
            hideRequiredMark
            initialValues={{ teacher_name: userInfo.username }}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="课程名称"
                  rules={[{ required: true, message: "请输入课程名称!" }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="teacher_name"
                  label="教课老师"
                  rules={[{ required: true, message: "Please enter url" }]}
                >
                  <Input disabled />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item label="开课时间" name="time">
                  <RangePicker></RangePicker>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="授课班级" name="_class">
                <Select
                  mode="multiple"
                  allowClear
                  style={{ width: "100%" }}
                  placeholder="请选择授课班级"
                >
                  {classList}
                </Select>
                </Form.Item>  
              </Col>
            </Row>
          </Form>
          <div className="updataImage">
            <div className="l">
              <p>课程封面</p>
              <span>可从下列图片中任意选择一张作为课程封面</span>
            </div>
            <div className="border l">
              {updataImg.length !== 0 ? <img src={updataImg} alt="" /> : ""}
            </div>
          </div>
          <div className="imgList">
            {images.map((e, index) => {
              return (
                <img
                  key={index}
                  src={e.default}
                  className="courseImg"
                  onClick={(e) => {
                    selectedImg(e);
                  }}
                  alt=""
                />
              );
            })}
          </div>
        </Drawer>
      </div>
      {list.map((e, index) => {
        return (
          <li className="l" key={index}>
            <CourseItem item={e} type={userInfo.type} />
          </li>
        );
      })}
    </div>
  );
};
export default Course;
